<template>
  <div class="app-container">
    <h2 style="text-align: center">{{ headTitle }}</h2>
    <div v-show="showBar">
      <el-steps
        :active="1"
        process-status="wait"
        align-center
        style="margin-bottom: 40px"
      >
        <el-step title="填写课程基本信息" />
        <el-step title="编辑课程目录" />
        <el-step title="最终发布" />
      </el-steps>
    </div>

    <el-form
      label-width="150px"
      :rules="rules"
      :model="courseInfo"
      ref="ruleForm"
    >
      <el-form-item label="课程标题" prop="title">
        <el-input v-model="courseInfo.title" placeholder=" 示例：XX课程。" />
      </el-form-item>

      <!-- 所属分类 TODO -->
      <el-form-item label="课程分类" prop="subjectParentId">
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="分类"
          @change="subjectLevelOneChanged"
          prop="subjectParentId"
        >
          <el-option
            v-for="subject in subjectOneList"
            :key="subject.id"
            :label="subject.courseName"
            :value="subject.id"
          />
        </el-select>

        <!-- 二级分类 -->
        <!-- <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
          <el-option
            v-for="subject in subjectTwoList"
            :key="subject.id"
            :label="subject.courseName"
            :value="subject.id"
          />
        </el-select> -->
      </el-form-item>
      <!-- 对应工种,复选框 -->
      <el-form-item label="适用工种" prop="subjectIds">
        <el-checkbox-group v-model="courseInfo.subjectIds">
          <el-checkbox
            v-for="subject in subjectTwoList"
            :key="subject.id"
            :label="subject.id"
          >
            {{ subject.courseName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="适用职级" prop="gradeId">
        <el-select v-model="courseInfo.gradeId" clearable>
          <el-option
            v-for="item in gradeList"
            :key="item.id"
            :label="item.grade"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学习路线" prop="kind">
        <el-select v-model="courseInfo.kind" clearable placeholder="请选择">
          <el-option
            v-for="item in kindList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程类型" prop="type">
        <el-radio v-model="courseInfo.type" label="理论">理论</el-radio>
        <el-radio v-model="courseInfo.type" label="实操">实操</el-radio>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfo.lessonNum"
          controls-position="right"
        />
      </el-form-item>

      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <el-input type="textarea" v-model="courseInfo.description"></el-input>
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面" prop="cover">
        <el-upload
          accept=".jpg, .jpeg, .png, .JPG, .JPEG"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="imgUrl"
          class="avatar-uploader"
        >
          <img width="200px" height="200px" :src="courseInfo.cover" />
        </el-upload>
      </el-form-item>

      <!-- <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        />
        元
      </el-form-item> -->

      <el-form-item style="padding: 10px 0; text-align: center">
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate('next')"
          plain
          >保存并下一步</el-button
        >
        <!-- 右方返回按钮 -->
        <el-button
          :disabled="saveBtnDisabled"
          type="success"
          @click="saveOrUpdate('back')"
          plain
          >保存并返回</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getCategory } from "@/api/classification";
import {
  getCourseInfoId,
  getGrade,
  addCourseInfo,
  updateCourseInfo,
} from "@/api/edu/course";

export default {
  data() {
    return {
      saveBtnDisabled: false,
      headTitle: "发布新课程",
      showBar: false, //是否展示步骤条
      courseInfo: {
        title: "",
        gradeId: "",
        subjectParentId: "", //一级分类id
        subjectId: "", //二级分类id
        subjectIds: [], //工种列表
        teacherId: "",
        lessonNum: 0,
        description: "",
        cover:
          "https://edu-gulicalss.oss-cn-hangzhou.aliyuncs.com/2021/09/20/ea1367668e8a42399a4ea91ae3397e08file.png",
        price: 0,
      },
      //路线列表
      kindList: [
        { value: "0", label: "新型学徒" },
        {
          value: "1",
          label: "重点用工",
        },
        {
          value: "2",
          label: "技能提升",
        },
      ],
      gradeList: null,
      courseId: "",
      //图片上传的地址
      imgUrl: process.env.BASE_API + "/coursewareOss/uploadOssCoursewareCover",
      subjectOneList: [], //一级分类
      subjectTwoList: [], //二级分类
      rules: {
        title: [
          { required: true, message: "请输入课程标题", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
        gradeId: [
          { required: true, message: "请选择课程职级", trigger: "blur" },
        ],
        // subjectId: [
        //   { required: true, message: "请选择课程分类", trigger: "blur" },
        // ],
        kind: [{ required: true, message: "请选择学习路线", trigger: "blur" }],
        type: [{ required: true, message: "请选择课程类型", trigger: "blur" }],
        cover: [{ required: true, message: "请上传课程封面", trigger: "blur" }],
        subjectParentId: [
          { required: true, message: "请选择课程分类", trigger: "blur" },
        ],
        subjectIds: [
          { required: true, message: "请选择适用工种", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //获取路由id值
    if (this.$route.params && this.$route.params.id) {
      this.headTitle = "编辑课程信息";
      this.courseId = this.$route.params.id;
      //调用根据id查询课程的方法
      this.getInfo();
    } else {
      this.showBar = true;
      //初始化所有职级
      this.getGradeList();
      //初始化一级分类
      this.getOneSubject();
    }
    this.getGradeList();
  },
  methods: {
    //根据课程id查询
    getInfo() {
      //初始化分类列表
      getCourseInfoId(this.courseId).then((response) => {
        //在courseInfo课程基本信息，包含 一级分类id 和 二级分类id
        this.courseInfo = response.data.courseInfoVo;
        //1 查询所有的分类，包含一级和二级
        //目的在于解决数据回写时 二级分类无法正常显示问题
        getCategory(0, this.companyId).then((response) => {
          //2 获取所有一级分类
          this.subjectOneList = response.data.resList;
          //3 把所有的一级分类数组进行遍历，
          for (var i = 0; i < this.subjectOneList.length; i++) {
            //获取每个一级分类
            var oneSubject = this.subjectOneList[i];
            //比较当前courseInfo里面一级分类id和所有的一级分类id
            if (this.courseInfo.subjectParentId == oneSubject.id) {
              //获取一级分类所有的二级分类
              this.subjectTwoList = oneSubject.childrenList;
            }
          }
        });
      });
    },
    //上传之前调用的方法
    beforeAvatarUpload(file) {},
    //上传封面成功调用的方法
    handleAvatarSuccess(res, file) {
      this.courseInfo.cover = res.data.url;
    },
    //点击某个一级分类，触发change
    subjectLevelOneChanged(value) {
      //value就是一级分类id值
      //遍历所有的分类，包含一级和二级
      for (var i = 0; i < this.subjectOneList.length; i++) {
        //每个一级分类
        var oneSubject = this.subjectOneList[i];
        //判断：所有一级分类id 和 点击一级分类id是否一样
        if (value === oneSubject.id) {
          //从一级分类获取里面所有的二级分类
          this.subjectTwoList = oneSubject.childrenList;
          //把二级分类id值清空
          this.courseInfo.subjectId = "";
        }
      }

      //清空工种列表
      this.courseInfo.subjectIds = [];
    },
    //查询所有的一级分类
    getOneSubject() {
      getCategory(0, this.companyId).then((response) => {
        this.subjectOneList = response.data.resList;
        this.subjectParentId = this.subjectOneList[0].id;
        this.subjectTwoList = this.subjectOneList[0].childrenList;
      });
    },
    //查询所有的职级
    getGradeList() {
      getGrade().then((res) => {
        if (res.success) {
          this.gradeList = res.data.resList;
        }
      });
    },
    //添加课程
    addCourse(type) {
      // 判断输入的信息是否完整
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //添加课程
          addCourseInfo(this.courseInfo).then((response) => {
            //提示
            this.$message({
              type: "success",
              message: "添加课程信息成功!",
            });
            //返回还是下一步
            if (type == "back") {
              this.$router.push({
                path: "/course",
              });
            } else {
              this.$router.push({
                path:
                  "/chapter/" +
                  response.data.courseId +
                  "/" +
                  this.courseInfo.subjectIds[0] +
                  "/" +
                  this.courseInfo.gradeId +
                  "/" +
                  this.courseInfo.kind,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    //修改课程
    updateCourse(type) {
      //判断输入的信息是否完整
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //修改课程
          updateCourseInfo(this.courseInfo).then((response) => {
            //提示
            this.$message({
              type: "success",
              message: "修改课程信息成功!",
            });
            //返回
            //返回还是下一步
            if (type == "back") {
              this.$router.push({
                path: "/course",
              });
            } else {
              this.$router.push({
                path:
                  "/chapter/" +
                  this.courseInfo.id +
                  "/" +
                  this.courseInfo.subjectIds[0] +
                  "/" +
                  this.courseInfo.gradeId +
                  "/" +
                  this.courseInfo.kind,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    //判断添加还是修改
    saveOrUpdate(type) {
      if (!this.courseInfo.id) {
        //添加
        this.addCourse(type);
      } else {
        //修改
        this.updateCourse(type);
      }
    },
  },
};
</script>
<style scoped>
</style>